<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *  抽奖管理
 *
 *  Author:  YSX
    Date:    2022-6-1
 */
class Prize extends Backend
{

    /**
     * Prize模型对象
     * @var \app\admin\model\Prize
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $searchFields = 'name,prize_code';
	protected $multiFields = ['is_enable'];
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

	/**
	 * 构建查询提交
	 * @return $query
	 * @Author YSX
	 * @DateTime 2023-08-9
	 */
	protected function buildSearchWhere()
	{
	    $isEnable = $this->request->get("is_enable");
	    $prizeIds = $this->request->get("prize_ids");
	    $prizeName = $this->request->get("prize_name", '');        // 关键字
	    $prize = Db::name('prize');
	    if ($prizeName) {
	        $prize = $prize->where('prize_name', "LIKE", "%{$prizeName}%");
	    }
	    if ($isEnable != '') {
	        $prize = $prize->where('is_enable', $isEnable);
	    }
	    if ($prizeIds) {
	        $prize = $prize->whereIn('id', $prizeIds);
	    }
	    return $prize;
	}
	
	public function index()
	{
	    //设置过滤方法
	    $this->request->filter(['strip_tags']);
	    if ($this->request->isAjax()) {
	        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
	        $total = $this->buildSearchWhere()->count();
	        $list = $this->buildSearchWhere()
	            ->order($sort, $order)
	            ->limit($offset, $limit)
	            ->select();
	        // foreach ($list as $item) {
	        //     $item->append(['tag_text']);
	        // }
	        $result = array("total" => $total, "rows" => $list);
	        return $this->success('操作成功', null, $result);
	    }
	    return $this->view->fetch();
	}
    // /**
    //  * 查看
    //  */
    // public function index()
    // {
    //     //设置过滤方法
    //     $this->request->filter(['strip_tags']);
    //     if ($this->request->isAjax()) {
    //         //如果发送的来源是Selectpage，则转发到Selectpage
    //         if ($this->request->request('keyField')) {
    //             return $this->selectpage();
    //         }

    //         list($where, $sort, $order, $offset, $limit) = $this->buildparams();
    //         $total = Db::name('prize')
    //             ->where($where)
    //             ->where('is_del',1)
    //             ->order($sort, $order)
    //             ->count();
    //         $list = Db::name('prize')
    //             ->where($where)
				// ->where('is_del',1)
    //             ->order($sort, $order)
    //             ->limit($offset, $limit)
    //             ->select();
    //         $list = collection($list)->toArray();
    //         $result = array("total" => $total, "rows" => $list);

    //         return json($result);
    //     }
    //     return $this->view->fetch();
    // }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                // 启动事务
                Db::startTrans();
                try {
                    //先添加商品主表
                    $params['add_time'] = time();
                    $result = Db::name('prize')->insertGetId($params);
                    // 提交事务
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = Db::name('prize')->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //先修改商品主表
                    $params['upd_time'] = time();
                    $result = Db::name('prize')->where('id',$row['id'])->update($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

   
    /**
     * 删除商品
     */
    public function delete()
    {
		$id = input('ids');
		$res = Db::name('prize')->where('id',$id)->update(['is_del'=>2]);
		if ($res !== false) {
		    $this->success();
		} else {
		    $this->error(__('删除失败'));
		}
    }
     /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }
}
